package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"time"
)

type Like struct {
	ID        int    `gorm:"primary_key"`
	Title     string `gorm:"type:varchar(128);not null;index:title_idx"`
	Hash      uint64 `gorm:"unique_index:hash_idx;"`
	CreatedAt time.Time
}


func main() {
	db, err := gorm.Open("mysql",
		"root:123qwe@/test?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println("connection succedssed")
	}
	defer db.Close()

	//创建表
	if !db.HasTable(&Like{}) {
		if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Like{}).Error; err != nil {
			panic(err)
		}
	}

	like := &Like{
		Title:     "for test",
		Hash:      163423421,
		CreatedAt: time.Now(),
	}

	if err := db.Create(like).Error; err != nil {
		fmt.Println(err)
	}else{
		fmt.Println("插入成功")
	}

	//查询
	var count int
	err = db.Model(&Like{}).Where(&Like{Title: "hello"}).Count(&count).Error
	if err != nil {
		fmt.Println(err)
	}else{
		fmt.Println(count)
	}

}